package org.muninn.niagara.conversion;

import javax.baja.status.BStatusBoolean;
import javax.baja.status.BStatusEnum;
import javax.baja.sys.BComponent;
import javax.baja.sys.BEnumRange;
import javax.baja.sys.BFacets;
import javax.baja.sys.BIcon;
import javax.baja.sys.BValue;
import javax.baja.sys.Context;
import javax.baja.sys.Flags;
import javax.baja.sys.Property;
import javax.baja.sys.Sys;
import javax.baja.sys.Topic;
import javax.baja.sys.Type;

public class BBooleanToTrigger extends BComponent
{
  private static final String[] keys = {"Rising", "Falling", "Either"};
  private static final int[] ordinals = {0, 1, 2};
  
  /** Boolean input to be monitored for changes **/
  public static final Property in = newProperty(Flags.SUMMARY, new BStatusBoolean(), null);
  public void setIn(BStatusBoolean v) { set(in, v); }
  public BStatusBoolean getIn() { return (BStatusBoolean) get(in); }
  
  /** Enum specifying which edge to fire topic on **/
  public static final Property edge = newProperty(Flags.SUMMARY, new BStatusEnum(), BFacets.makeEnum(BEnumRange.make(ordinals, keys)));
  public void setEdge(BStatusEnum v) { set(edge, v); }
  public BStatusEnum getEdge() { return (BStatusEnum) get(edge); }
  
  /** Output to be fired **/
  public static final Topic trigger = newTopic(0, null);
  public void fireTrigger(BValue v) { fire(trigger, v, null); }
  
  private boolean prevIn;
  
  public void started() { prevIn = getIn().getValue(); }
  
  public void changed(Property p, Context cx)
  {
    if (p.equals(in))
    {
      if (getEdge().getValue().getOrdinal() == 0)
      {
        if (getIn().getValue() && !prevIn)
        {
          prevIn = true;
          fireTrigger(null);
        }
      }
      
      else if (getEdge().getValue().getOrdinal() == 1)
      {
        if (!(getIn().getValue()) && prevIn)
        {
          prevIn = false;
          fireTrigger(null);
        }
      }
      
      else
      {
        prevIn = !prevIn;
        fireTrigger(null);
      }
    }
  }
  
  public BIcon getIcon() { return icon; }
  private static final BIcon icon = BIcon.make("local:|module://muninn/org/muninn/niagara/graphics/MuninnGroup.PNG");

  public static final Type TYPE = Sys.loadType(BBooleanToTrigger.class);
  public Type getType() { return TYPE; }
}
